package com.swak.frame.excel.validation;


import com.swak.frame.excel.metadata.ExcelRow;
import com.swak.frame.exception.ExcelException;
import com.swak.frame.util.GetterUtil;
import com.swak.frame.validation.ValidationResult;
import org.apache.commons.collections4.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public interface RowDataValidator<T extends ExcelRow> {

	ValidationResult validate(T data);

	default boolean validate(T data, Map<String, Integer> cellMap) {
		int rowIndex  = data.getRowIndex();
		ValidationResult validResult = validate(data);
		if (!validResult.isSuccess()) {
			ValidationResult.ErrorMessage errorMessage = validResult.getErrorMessages().get(0);
			Integer columnIndex = cellMap.get(errorMessage.getPropertyName());
			if (columnIndex != null) {
				Map<Integer, List<String>> rowHeader = Optional.ofNullable(data.getRowHead())
						.orElse(Collections.emptyMap());
				String propertyNameShow = errorMessage.getPropertyName();
				List<String> propertyNameList = rowHeader.get(columnIndex);
				if(CollectionUtils.isNotEmpty(propertyNameList)) {
					propertyNameShow = propertyNameList.get(0);
				}
				throw new ExcelException(String.format("[%s] 第%s行第%s列的值%s",
						new Object[] {GetterUtil.getString(propertyNameShow,errorMessage.getPropertyName()), (rowIndex + 1), (columnIndex+1),errorMessage.getMessage()}));
			} else {
				throw new ExcelException("["+errorMessage.getPropertyName()+"] 第" + (rowIndex + 1) + "行数据" + errorMessage.getMessage());
			}
		}
		return true;
	}

	public static <T> RowDataValidator<ExcelRow> defaultValidator() {
		return (data) -> new ValidationResult(true);
	}
}
